package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {

        //用户正常登录手机号和密码
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //1.判断用户是否存在
//            LambdaQueryChainWrapper<ApUser> wrapper = new LambdaQueryChainWrapper<ApUser>();
//            wrapper.eq(ApUser::getPhone, dto.getPhone());
//            this.getOne(wrapper);
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            //2.判断密码是否正确
            String loginPwd = dto.getPassword();//用户登录的明文密码
            String dbPwd = apUser.getPassword();//用户表中的密文密码
            boolean result = BCrypt.checkpw(loginPwd, dbPwd);
                //2.1密码不正确，提示密码错误
            if (!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
                //2.2密码正确，使用jwt生成token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword(null);
            Map map = new HashMap();
            map.put("user",apUser);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }else{//游客登录
            String token = AppJwtUtil.getToken(0L);
           Map map = new HashMap();
           map.put("token",token);
           return ResponseResult.okResult(map);
        }
    }
}
